//
//  ReceivePigViewController.m
//  PigMarket
//
//  Created by mac on 2019/5/10.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "ReceivePigViewController.h"
#import "ReceiveCell.h"
#import "PayTypeView.h"

@interface ReceivePigViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
/**
 collectionView
 */
@property (nonatomic , strong) UICollectionView *collectionView;

/**
 headIMg
 */
@property (nonatomic , strong) UIImageView *headImg;
/**
 title
 */
@property (nonatomic , strong) UILabel *receiveTitle;
/**
 receiveTime
 */
@property (nonatomic , strong) UILabel *receiveTime;
/**
 line
 */
@property (nonatomic , strong) UIView *line;
/**
 j拒绝Btn
 */
@property (nonatomic , strong) UIButton *refuseBtn;
/**
 receiveBtn
 */
@property (nonatomic , strong) UIButton *receiveBtn;
/**
 已收到仔猪title
 */
@property (nonatomic , strong) UILabel *receivedNum;
/**
 dataArr
 */
@property (nonatomic , strong) NSMutableArray *dataArr;
/**
 assignmentId
 */
@property (nonatomic , assign) NSNumber *assignmentId;
/**
 selectIndex
 */
@property (nonatomic , assign) NSInteger selectIndex;
/**
 转让金额
 */
@property (nonatomic , strong) NSString *transferMoney;
@end

@implementation ReceivePigViewController


#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"仔猪接收";
    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpView];
}


#pragma mark - init method
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}


- (void)initView {
    [self.view addSubview:self.headImg];
    [self.view addSubview:self.receiveTitle];
    [self.view addSubview:self.receiveTime];
    [self.view addSubview:self.line];
    [self.view addSubview:self.receivedNum];
    [self.view addSubview:self.refuseBtn];
    [self.view addSubview:self.receiveBtn];
    
    [self.view addSubview:self.collectionView];
}



- (void) initLayout {
    

    [self.headImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(28);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    [self.receiveTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.headImg.mas_bottom).offset(20);
        make.height.mas_equalTo(25);
        make.centerX.mas_equalTo(self.view.mas_centerX);
    }];
    [self.receiveTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(self.receiveTitle.mas_bottom).offset(8);
        make.height.mas_equalTo(18);
    }];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.receiveTime.mas_bottom).offset(20);
        make.height.mas_equalTo(1);
        make.left.right.mas_equalTo(0);
    }];
    [self.receivedNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(self.line.mas_bottom).offset(15);
        make.height.mas_equalTo(20);
    }];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(self.receivedNum.mas_bottom).offset(0);
        make.height.mas_equalTo(310);
        make.width.mas_equalTo(SCREEN_WIDTH);
    }];
    [self.refuseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.collectionView.mas_bottom).offset(30);
        make.left.mas_equalTo(52);
        make.size.mas_equalTo(CGSizeMake(126, 36));
    }];
    [self.receiveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.collectionView.mas_bottom).offset(30);
        make.right.mas_equalTo(-52);
        make.size.mas_equalTo(CGSizeMake(126, 36));
    }];
}


- (void) initAction {
    [self.refuseBtn addTarget:self action:@selector(refuseTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.receiveBtn addTarget:self action:@selector(receiveTapped) forControlEvents:UIControlEventTouchUpInside];
}



- (void)initData {
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] receivePigWithMemberId:memberId] subscribeNext:^(ReceivePigList * _Nullable receivePigList) {
        @strongify(self);
        [self.dataArr addObjectsFromArray:receivePigList.list];
        

        //头部数据赋值
        if (self.dataArr.count > 0) {
            [self refreshHeaderDataWithIndx:0];
            
//            //默认选中第一个
//            ReceivePig *model = self.dataArr[0];
//            model.isSelect = YES;
//            self.assignmentId = model.assignmentId;
//            self.transferMoney = [NSString stringWithFormat:@"%@",model.money];
        }
        [self.collectionView reloadData];
    } error:^(NSError * _Nullable error) {
       
        @strongify(self);
        [self handlingError:error];
    }];
}


- (void)refreshHeaderDataWithIndx:(NSUInteger)index {
 
        ReceivePig *model = self.dataArr[index];
        [self.headImg sd_setImageWithURL:[NSURL URLWithString:model.headImg] placeholderImage:[UIImage imageNamed:@"placeholder_middle"]];
        self.receiveTitle.text = [NSString stringWithFormat:@"收到%@转让的仔猪",model.nickName];
        self.receiveTime.text = model.countdown;
        self.receivedNum.text = [NSString stringWithFormat:@"已收到仔猪%lu头",(unsigned long)self.dataArr.count];
}



#pragma mark - delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ReceiveCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ReceiveCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    if (self.dataArr.count > indexPath.item) {
        [cell configCellWithModel:self.dataArr[indexPath.row]];
    }
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    [self.dataArr enumerateObjectsUsingBlock:^(ReceivePig *model, NSUInteger idx, BOOL * _Nonnull stop) {
        if (indexPath.item == idx) {
            model.isSelect = YES;
        } else {
            model.isSelect = NO;
        }
        self.assignmentId = model.assignmentId;
        self.selectIndex = indexPath.item;
        self.transferMoney = [NSString stringWithFormat:@"%@",model.money];
    }];
    [self refreshHeaderDataWithIndx:indexPath.item];
    [self.collectionView reloadData];
}


#pragma mark - target action
//拒绝
- (void)refuseTapped {

    [self receiveStatusRequestWithType:ReceiveTypeRefuse payType:PayTypeNull];
}


//同意
- (void)receiveTapped {
    PayTypeView *payView = [[PayTypeView alloc] initWithFrame:CGRectMake(0, 620, SCREEN_WIDTH, 160)];
    [self.view addSubview:payView];
    @weakify(self);
    [payView setPayTypeBlock:^(PayType payType) {
        @strongify(self);
        //同意接受 --> 获取三方支付参数 --> 校验接口
        [self agreeRequestWithPayType:payType];
    }];
}


#pragma mark - private method
//获取三方支付参数 --> 校验接口
- (void)agreeRequestWithPayType:(PayType)payType {
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    
    //获取三方支付参数
    GetThirdPayParam *param = [[GetThirdPayParam alloc] init];
    param.assignmentId = self.assignmentId;
    param.memberId = memberId;
    param.money = self.transferMoney;
    param.payType = @(payType);
    @weakify(self);
    [[[PigMarketApi sharedInstance] receivePigToGetThirdPayParamWithParam:param] subscribeNext:^(Pay * _Nullable pay) {
        
        
        [[PayManager sharedManager] payWithWeChatMethod:pay callBack:^(PayErrCode errCode, NSString *errStr) {
            @strongify(self);
            if (errCode == PayErrCodeSuccess) {
                //校验接口
                [self receiveStatusRequestWithType:ReceiveTypeAgree payType:payType];
            } else {
                [self toastWithContent:errStr];
            }
                
        }];
  
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}


/**
 接收校验 拒绝
 @param type 接收类型  同意和拒绝
 @param payType 支付方式
 */
- (void)receiveStatusRequestWithType:(ReceiveType)type payType:(PayType)payType{
    
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] receiveStatusWithAssignmentId:self.assignmentId type:@(type) payType:@(payType)] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        switch (type) {
            case ReceiveTypeAgree:
            {
                [self toastWithContent:@"接收成功"];
               
            }
                break;
            case ReceiveTypeRefuse:
            {
                [self toastWithContent:@"拒绝成功"];

            }
                break;
            default:
                break;
        }
        //刷新数据
        [self.dataArr removeObjectAtIndex:self.selectIndex];
        [self.collectionView reloadData];
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}


#pragma mark - getter and setter
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat itemW = 320;
        CGFloat itemH = 310;
        layout.itemSize = CGSizeMake(itemW, itemH);
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[ReceiveCell class] forCellWithReuseIdentifier:@"ReceiveCell"];
    }
    return _collectionView;
}


- (UIImageView *)headImg {
    if (!_headImg) {
        _headImg = [[UIImageView alloc] init];
    }
    return _headImg;
}


- (UILabel *)receiveTitle {
    if (!_receiveTitle) {
        _receiveTitle = [[UILabel alloc] init];
        _receiveTitle.textColor = [UIColor textBlackColor];
        _receiveTitle.font = [UIFont xLargerFont];
    }
    return _receiveTitle;
}


- (UILabel *)receiveTime {
    if (!_receiveTime) {
        _receiveTime = [[UILabel alloc] init];
        _receiveTime.textColor = [UIColor colorWithHexString:@"#F25C62"];
        _receiveTime.font = [UIFont systemFontOfSize:13];
    }
    return _receiveTime;
}


- (UIView *)line {
    if (!_line) {
        _line = [[UIView alloc] init];
        _line.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.08];
    }
    return _line;
}


- (UILabel *)receivedNum {
    if (!_receivedNum) {
        _receivedNum = [[UILabel alloc] init];
        _receivedNum.textColor = [UIColor textBlackColor];
        _receivedNum.font = [UIFont middleFont];
    }
    return _receivedNum;
}


- (UIButton *)refuseBtn {
    if (!_refuseBtn) {
        _refuseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_refuseBtn setTitle:@"果断拒绝" forState:UIControlStateNormal];
        [_refuseBtn setTitleColor:[UIColor colorWithHexString:@"#454545"] forState:UIControlStateNormal];
        _refuseBtn.titleLabel.font = [UIFont largerFont];
        _refuseBtn.layer.borderColor = [UIColor colorWithHexString:@"#D8D8D8"].CGColor;
        _refuseBtn.layer.borderWidth = 1;
        _refuseBtn.layer.cornerRadius = 18;
        _refuseBtn.layer.borderWidth = 1;
    }
    return _refuseBtn;
}


- (UIButton *)receiveBtn {
    if (!_receiveBtn) {
        _receiveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_receiveBtn setTitle:@"确认接收" forState:UIControlStateNormal];
        [_receiveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _receiveBtn.titleLabel.font = [UIFont largerFont];
        [_receiveBtn setBackgroundImage:[UIImage imageNamed:@"pay_result_btn_bg"] forState:UIControlStateNormal];
    }
    return _receiveBtn;
}


- (NSMutableArray *)dataArr {
    if ((!_dataArr)) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}


@end
